package com.kaikeba.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
 * @Author: Gyx
 * @Date: 2021/2/18 22:45
 */
public class DruidUtil {
    private static DataSource ds;

    /**
     * 静态代码块，通过德鲁伊连接池获取数据源对象
     */
    static {
        try {
            Properties ppt = new Properties();
            ppt.load(DruidUtil.class.getClassLoader().getResourceAsStream("druid.properties"));
            ds = DruidDataSourceFactory.createDataSource(ppt);
        }  catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取Connection链接对象
     * @return
     */
    public Connection getConnection(){
        try {
            return ds.getConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 关闭资源
     * @param conn 链接对象
     * @param stat 执行环境对象
     * @param rs 结果集对象
     */
    public void close(Connection conn , Statement stat, ResultSet rs){
        try {
            rs.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            stat.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
